const http = require('http');
const url = require('url');
const puppeteer = require('puppeteer');

let page; // Declare a global variable to store the page

async function getPuppeteerRenderedPage(url) {
  if (!page) {
  //  const browser = await puppeteer.launch({
	//	headless: "new",
	//	executablePath: "",
	//},
	//);


    const browser = await puppeteer.launch({
    headless: false, // Set headless to false to display the browser
   // executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', // Replace with the actual path
 // userDataDir:'f:\\chrometest',
 // executablePath:'C:\\Users\\Administrator\\Downloads\\chrome-win\\chrome-win\\chrome.exe',
  // userDataDir: 'C:\\Users\\administrator\\AppData\\Local\\Google\\Chrome\\User Data', // Replace with the actual user data directory path
	//args: ['--proxy-server=http://127.0.0.1:10809'] // Set up the HTTP proxy
  });
  
	const pages = await browser.pages();
    page = pages[0];
  }

  try {
    //await page.setViewport({ width: 1, height: 1 });
   // await page.goto(url, { waitUntil: 'domcontentloaded' });
	await page.goto(url, { waitUntil: 'networkidle0' });

  //  await page.waitForTimeout(2000);
  await page.evaluate(() => {
    window.scrollBy(0, 500);
});
await page.waitForTimeout(2000);
    const renderedContent = await page.content();
		   // 获取当前时间戳
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] ${url} 加载完成`);
    return renderedContent;
  } catch (error) {
    console.error('Error in getPuppeteerRenderedPage:', error);
    throw error; // Rethrow the error so it can be caught in the request handler
  }
}

const server = http.createServer(async (req, res) => {
  const query = url.parse(req.url, true).query;
  const requestedUrl = query.url;

  if (!requestedUrl) {
    res.writeHead(400, { 'Content-Type': 'text/plain' });
    res.end('Missing "url" parameter');
    return;
  }

  try {
    const renderedContent = await getPuppeteerRenderedPage(requestedUrl);

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(renderedContent);
  } catch (error) {
    console.error('Error in request handler:', error);

    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Internal Server Error');
  }
});

const PORT = 3000;

server.listen(PORT,"0.0.0.0", () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
